package persistent.prestige.console.netty.dubbo.net.heart;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import persistent.prestige.console.netty.dubbo.net.NettyClientConnection;

/**
 * 心跳检测
 * @author dingwei2
 *
 */
public class HeartExecutorThreadPool extends ScheduledThreadPoolExecutor {
	
	private NettyClientConnection connection;
	private int allowedFailCount;
	private int failCount;

	public HeartExecutorThreadPool(int corePoolSize) {
		super(corePoolSize);
		// TODO Auto-generated constructor stub
	}
	
	public HeartExecutorThreadPool(int corePoolSize, NettyClientConnection connection, int allowedFailCount) {
		super(corePoolSize);
		// TODO Auto-generated constructor stub
		this.connection = connection;
		this.allowedFailCount = allowedFailCount;
	}

	@Override
	protected void afterExecute(Runnable r, Throwable t) {
		// TODO Auto-generated method stub
		super.afterExecute(r, t);
		
		if(t != null ) { //目前这里粗糙的，只要认为发生了异常，就认为通道不可用
			if(++ failCount >= allowedFailCount ) { //如果连续发生错误的次数大于等于允许的最大失败次数，则认为通道关闭
				connection.close();//关闭通道
			}
		} else {
			failCount = 0;
		}
		
	}
	
	
	

}
